import * as vscode from 'vscode';
import * as gitLabService from '../gitlab_service';
import { ErrorItem } from './items/error_item';
import { handleError } from '../log';
import { ItemModel } from './items/item_model';
import { extensionState } from '../extension_state';
import { gitExtensionWrapper } from '../git/git_extension_wrapper';
import { SnippetItem } from './items/snippet_item';


export class DataProvider implements vscode.TreeDataProvider<ItemModel | vscode.TreeItem> {
  private eventEmitter = new vscode.EventEmitter<void>();

  private disposableChildren: vscode.Disposable[] = [];

  onDidChangeTreeData = this.eventEmitter.event;

  constructor() {
    extensionState.onDidChangeValid(this.refresh, this);
  }

  async getChildren(item: ItemModel | undefined): Promise<ItemModel[] | vscode.TreeItem[] | undefined> {
    if (item) return item.getChildren();
    this.disposableChildren.forEach(s => s.dispose());
    this.disposableChildren = [];
    const repository = gitExtensionWrapper.getActiveRepository();
    if (!extensionState.isValid() || !repository) {
      return [];
    }
    try {
      const gitlabProject = await repository.getProject();
      if (!gitlabProject) {
        return [];
      }
      const projectCodeSnippets = await gitLabService.fetchSnippetForCurrentUser();
      if (projectCodeSnippets.length === 0){
        return [new vscode.TreeItem('未在当前项目下发现代码笔记')];
      }
      const snippets = projectCodeSnippets.map((s: RestCodeSnippet) => new SnippetItem(s.id, s.title));
      return snippets;
    } catch (e) {
      handleError(e);
      return [new ErrorItem()];
    }
  }


  // eslint-disable-next-line class-methods-use-this
  getParent(): null {
    return null;
  }

  // eslint-disable-next-line class-methods-use-this
  getTreeItem(item: vscode.TreeItem | ItemModel) {
    if (item instanceof ItemModel) return item.getTreeItem();
    return item;
  }

  refresh(): void {
    this.eventEmitter.fire();
  }
}
